#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2025/10/3 18:37
# @Author  : summer
# @Email   : 610658552@qq.com
# @File    : filter_schooldistrict.py.py
# @Software: PyCharm
# @Desc    :
import django_filters
from oa.models import SchoolDistrict
from django.core.validators import MinValueValidator


def strip_filter(value):
    """去除字符串前后空格"""
    if isinstance(value, str):
        return value.strip()
    return value


class SchoolDistrictFilter(django_filters.FilterSet):
    """校区表过滤器"""
    # 校区名称：模糊查询（忽略大小写）
    name = django_filters.CharFilter(lookup_expr='icontains', method='filter_name')
    # 负责人姓名：模糊查询
    contact_name = django_filters.CharFilter(lookup_expr='icontains', method='filter_contact_name')
    # 负责人电话：显式注册为模糊查询（关键修复）
    contact_tel = django_filters.CharFilter(lookup_expr='icontains', method='filter_contact_tel')
    # 状态：精确匹配（0禁用/1启用）
    status = django_filters.NumberFilter(
        field_name='status',
        lookup_expr='exact',
        validators=[MinValueValidator(0)]  # 状态最小为0
    )
    # 地址：模糊查询
    address = django_filters.CharFilter(lookup_expr='icontains', method='filter_address')

    def filter_name(self, queryset, name, value):
        """过滤校区名称（去空格后模糊匹配）"""
        value = strip_filter(value)
        return queryset.filter(name__icontains=value) if value else queryset

    def filter_contact_name(self, queryset, name, value):
        """过滤负责人姓名（去空格后模糊匹配）"""
        value = strip_filter(value)
        return queryset.filter(contact_name__icontains=value) if value else queryset

    def filter_contact_tel(self, queryset, name, value):
        """过滤负责人姓名（去空格后模糊匹配）"""
        value = strip_filter(value)
        return queryset.filter(contact_tel__icontains=value) if value else queryset

    def filter_address(self, queryset, name, value):
        """过滤地址（去空格后模糊匹配）"""
        value = strip_filter(value)
        return queryset.filter(address__icontains=value) if value else queryset

    def filter_description(self, queryset, name, value):
        """过滤地址（去空格后模糊匹配）"""
        value = strip_filter(value)
        return queryset.filter(description__icontains=value) if value else queryset

    class Meta:
        model = SchoolDistrict
        # 支持的过滤字段（包含自动生成的精确匹配过滤）
        fields = ['name', 'status', 'contact_name', 'contact_tel', 'description', 'address', 'is_delete']

    @property
    def qs(self):
        """重写查询集，默认只返回未删除的数据（is_delete=0）"""
        parent = super().qs
        return parent.filter(is_delete=0)
